Ext.ns('AIR2.UI');
/***************
 * AIR2 AnnotationPanel Component
 *
 * AIR2 Panel for adding/editing/viewing annotations on a resource.
 *
 * @class AIR2.UI.AnnotationPanel
 * @extends AIR2.UI.Panel
 * @xtype air2annotationpanel
 * @cfg {String} valueField
 *   Data field containing the annotation value to display.
 * @cfg {String} creField
 *   Data field containing the annotation creation dtim
 * @cfg {String} updField
 *   Data field containing the annotation update dtim
 * @cfg {String} winTitle
 *   Optional title to give the modal annotation window
 * @cfg {Object/Array} storeData
 *   Initial annotation data to load
 * @cfg {String} url
 *   Restful url to access annotations
 * @cfg {Boolean} allowEdit
 *   False to disable adding/editing/deleting annotations. (default true)
 *
 */
AIR2.UI.AnnotationPanel = function(cfg) {
    // add class
    if (!cfg.cls) cfg.cls = '';
    cfg.cls = 'air2-annotationpanel ' + cfg.cls;

    // references to field names
    var valueField = cfg.valueField;

    // create the panel template, if not supplied
    if (!cfg.tpl) {
        cfg.itemSelector = "air2-annotation-panel";
        cfg.tpl = new Ext.XTemplate(
            '<table>' +
              '<tpl for="."><tr class="air2-annotation-panel">' +
                '<td>{' + cfg.valueField + ':ellipsis(75)}</td>' +
                '<td class="author">{[AIR2.Format.userName(values.CreUser, true)]}</td>' +
                '<td>{[AIR2.Format.date(values.' + cfg.updField + ')]}</td>' +
              '</tr></tpl>' +
            '</table>',
            {compiled: true, disableFormats: false}
        );
    }

    // create the modal window config
    var userMayWrite = (cfg.allowEdit == false) ? false : true;
    cfg.editModal = {
        title: (cfg.winTitle) ? cfg.winTitle : 'Annotations',
        allowAdd: userMayWrite,
        items: {
            xtype: 'air2liveeditor',
            url: cfg.url,
            sortField: cfg.creField,
            sortDir: 'DESC',
            pageSize: 25,
            editForm: {
                items: [{
                    xtype: 'textarea',
                    fieldLabel: 'Annotation',
                    name: valueField,
                    grow: true,
                    growMin: 100
                }]
            },
            allowEdit: userMayWrite,
            allowDelete: userMayWrite,
            hideButtons: true,
            tpl: new Ext.XTemplate(
                '<tpl for="."><table class="air2-annotation-item"><tr>' +
                  '<td class="who">' +
                    '<div class="info air2-corners" style="min-height:30px">' +
                      '{[AIR2.Format.userPhoto(values.CreUser, 50)]}' +
                      '<strong>{[AIR2.Format.userName(values.CreUser, true)]}</strong>' +
                      '{[this.sysuser(values.CreUser)]}' +
                      '<p>{[AIR2.Format.userOrgTitle(values.CreUser.UserOrg[0],20)]}</p>' +
                      '<div style="padding-top:5px">' +
                        '{[AIR2.Format.userOrgShort(values.CreUser.UserOrg[0], true)]}' +
                      '</div>' +
                    '</div>' +
                  '</td>' +
                  '<td class="text">' +
                    '<p>{' + cfg.valueField + '}</p>' +
                    '<div class="meta">' +
                      '<table><tr>' +
                        '<td>{[this.postdate(values)]}</td>' +
                        '<tpl if="this.showedit(values)">' +
                          '<td><button class="air2-rowedit"></button></td>' +
                          '<td><button class="air2-rowdelete"></button></td>' +
                        '</tpl>' +
                      '</tr></table>' +
                    '</div>' +
                  '</td>' +
                '</tr></table></tpl>',
                {
                    compiled: true,
                    disableFormats: true,
                    sysuser: function(u) {
                        return (u.user_type == 'S') ? '<p>System User</p>' : '';
                    },
                    postdate: function(v) {
                        if (v[cfg.updField] > v[cfg.creField])
                            return 'Updated ' + AIR2.Format.dateLong(v[cfg.updField]);
                        else
                            return 'Posted ' + AIR2.Format.dateLong(v[cfg.creField]);
                    },
                    showedit: function(v) {
                        return (AIR2.USERINFO.uuid == v.CreUser.user_uuid);
                    }
                }
            )
        },
        listeners: {
            render: function(w) {
                w.el.on('click', function(e) {
                    if (e.getTarget('.air2-rowedit')) {
                        var dv = w.get(0);
                        var n = e.getTarget(dv.itemSelector);
                        var r = dv.getRecord(n);
                        var p = new Ext.Container({
                            renderTo: document.createElement('td'),
                            cls: 'text',
                            items: [{
                                xtype: 'textarea',
                                grow: true,
                                growMin: 40,
                                width: '100%'
                            },{
                                xtype: 'air2button',
                                text: 'Save',
                                air2type: 'SAVE',
                                handler: function(btn) {
                                    r.set(valueField, btn.previousSibling().getValue());
                                    if (r.dirty) r.store.save();
                                    else dv.refreshNode(dv.indexOf(n));
                                    p.destroy();
                                }
                            },{
                                xtype: 'air2button',
                                text: 'Cancel',
                                air2type: 'CANCEL',
                                handler: function() {
                                    dv.refreshNode(dv.indexOf(n));
                                    p.destroy();
                                }
                            }]
                        });

                        // render (and replace existing)
                        p.el.replace(e.getTarget('.text'));
                        p.get(0).setValue(r.get(valueField));
                        e.stopEvent();
                    }
                    else if (e.getTarget('.air2-rowdelete')) {
                        dv = w.get(0);
                        n = e.getTarget(dv.itemSelector);
                        r = dv.getRecord(n);
                        dv.createDeleter(r, n, e.getTarget('.air2-rowdelete'));
                    }
                });
            }
        }
    };

    Ext.applyIf(cfg, this);
    AIR2.UI.AnnotationPanel.superclass.constructor.call(this, cfg);
}
Ext.extend(AIR2.UI.AnnotationPanel, AIR2.UI.Panel, {
    colspan: 1,
    title: 'Annotations',
    iconCls: 'air2-icon-annotation',
    showTotal: true
});